package com._520it.crm.web.controller;

import com._520it.crm.domain.Employee;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.EmployeeQueryObject;
import com._520it.crm.service.IEmployeeService;
import com._520it.crm.util.AjaxResult;
import com._520it.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @描述:
 * @作者:瓜
 * @create 2020/11/3
 */
@Controller
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/employee")
    public String index() {
        return "employee";
    }

    @ResponseBody
    @RequestMapping("/employee_list")
    public PageResult list(EmployeeQueryObject qo){
        PageResult result=null;
        result=employeeService.queryForPage(qo);
        return result;
    }

    @ResponseBody
    @RequestMapping("/employee_save")
    public AjaxResult save(Employee emp){
        AjaxResult result = null;
        try {
            emp.setPassword("123");
            emp.setAdmin(false);
            emp.setState(true);
            employeeService.insert(emp);
            result=new AjaxResult(true,"保存成功");
        }catch (Exception e){
            //写日志文件
            result=new AjaxResult("保存异常，请联系管理员");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/employee_update")
    public AjaxResult update(Employee emp){
        AjaxResult result = null;
        try {
            employeeService.updateByPrimaryKey(emp);
            result=new AjaxResult(true,"更新成功");
        }catch (Exception e){
            //写文件日志
            result=new AjaxResult("更新异常，请联系管理员");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/employee_delete")
    public AjaxResult delete(Long id){
        AjaxResult result = null;
        try {
            employeeService.updateState(id);
            result=new AjaxResult(true,"离职成功");
        }catch (Exception e){
            //写文件日志
            result=new AjaxResult("离职异常，请联系管理员");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/login")
    public AjaxResult login(String username, String password, HttpServletRequest request) {
        UserContext.set(request);
        AjaxResult result = null;
        Employee employeeUSer = employeeService.getEmployeeServiceFindLogin(username, password);
        if (employeeUSer != null) {
            request.getSession().setAttribute(UserContext.USERINSESSION,employeeUSer);
            result=new AjaxResult(true,"登录成功");
        } else {
            result=new AjaxResult("账号密码有误");
        }
        return result;
    }
}
